package com.atguigu.srb.core.controller.api;


import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.utils.RegexValidateUtils;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.LoginVO;
import com.atguigu.srb.core.pojo.vo.RegisterVO;
import com.atguigu.srb.core.pojo.vo.UserInfoVO;
import com.atguigu.srb.core.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户基本信息 前端控制器
 * </p>
 *
 * @author Mr.bilal
 * @since 2023-07-18
 */
@RestController
@RequestMapping("/api/core/userInfo")
//@CrossOrigin
public class ApiUserInfoController {

    @Autowired
    UserInfoService userInfoService;

    @PostMapping("/register")
    public R register(@RequestBody RegisterVO registerVO){
        String mobile = registerVO.getMobile();
        Integer userType = registerVO.getUserType();
        String code = registerVO.getCode();
        String password = registerVO.getPassword();
        Assert.isTrue(!StringUtils.isEmpty(mobile)&&!StringUtils.isEmpty(userType)&&!StringUtils.isEmpty(code)&&!StringUtils.isEmpty(password), ResponseEnum.COMMON_ERROR);
        boolean b = RegexValidateUtils.checkCellphone(mobile);
        Assert.isTrue(b,ResponseEnum.MOBILE_ERROR);
        userInfoService.register(registerVO);

        return R.ok();
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginVO loginVO, HttpServletRequest request){
        //获取ip地址
        //正常登录
//        String remoteAddr = request.getRemoteAddr();
        //用nginx登录
        String ip = request.getHeader("X-forwarded-for");
        String mobile = loginVO.getMobile();
        String password = loginVO.getPassword();
        Integer userType = loginVO.getUserType();
        Assert.isTrue(!StringUtils.isEmpty(mobile) &&!StringUtils.isEmpty(password)&& null != userType,ResponseEnum.COMMON_ERROR);
        UserInfoVO userInfoVO = userInfoService.login(loginVO,ip);
        return R.ok().data("userInfoVo",userInfoVO);
    }

    @GetMapping("/isMobileExist/{mobile}")
    public boolean isMobileExist(@PathVariable String mobile){
        return userInfoService.isMobileExist(mobile);
    }

    @GetMapping("/sentinel/test")
    public String sentinel(){
        return "ok";
    }


    @GetMapping("/getUserInfoByMobile/{mobile}")
    public R getUserInfoByMobile(@PathVariable String mobile){
        UserInfo userInfo = userInfoService.getUserInfoByMobile(mobile);
        return R.ok().data("userInfo",userInfo);
    }

}

